package com.xuecheng.checkcode.domain.template.impl;

import cn.hutool.core.util.RandomUtil;
import com.xuecheng.checkcode.domain.model.dto.CheckCodeGenerateDto;
import com.xuecheng.checkcode.domain.template.AbstractCheckCodeTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-07  18:27
 */
@Component("redisCheckCodeTemplate")
public class RedisCheckCodeTemplate extends AbstractCheckCodeTemplate {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String getKey(String prefix) {
        String random = RandomUtil.randomString(7);
        return prefix + "redis:" + random + ":";
    }

    @Override
    public void save(CheckCodeGenerateDto checkCodeGenerateDto) {
        stringRedisTemplate.opsForValue().set(checkCodeGenerateDto.getKey(), checkCodeGenerateDto.getValue(), 5, TimeUnit.MINUTES);
    }

    @Override
    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 检查是否达到最大值值，若达到就返回ture，否则返回false
     * @param key
     * @return
     */
    public Boolean checkErrorTime(String key){
        String errorKey = getErrorKey(key);
        String s = stringRedisTemplate.opsForValue().get(errorKey);
        Integer count = 1;
        if (Objects.nonNull(s)){
            count = Integer.parseInt(s) + 1;
        }
        if (count >= 3){
            // 达到最大值
            stringRedisTemplate.opsForValue().set(getBanKey(key), "1", 3, TimeUnit.MINUTES);
            return true;
        }
        stringRedisTemplate.opsForValue().set(errorKey, count.toString(), 1, TimeUnit.MINUTES);

        return false;
    }

    @Override
    public String getErrorKey(String str){
        return str + "error:";
    }

    @Override
    public void deleteKey(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 检查是否被冻结，true是，false否
     * @param key
     * @return
     */
    @Override
    public Boolean isBan(String key) {
        return Objects.nonNull(stringRedisTemplate.opsForValue().get(getBanKey(key)));
    }

    @Override
    public String getBanKey(String key) {
        return key + "ban:";
    }
}
